"use client";
import React, { useRef, useEffect, memo, useCallback } from "react";
import * as THREE from "three";
// 轨道控制器
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// glTF 2.0 模型加载器
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
// 加载经过Draco压缩的图形库
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { useTheme } from "next-themes";

const screenSize = {
  width: 900,
  height: 800,
};
function Room() {
  const roomModel = useRef<HTMLDivElement>(null);
  const { theme } = useTheme();

  const onLoadModel = useCallback(() => {
    // if (roomModel.current?.hasChildNodes()) return;
    if (roomModel.current?.firstChild)
      roomModel.current?.removeChild(roomModel.current?.firstChild);
    // 创建场景
    const scene = new THREE.Scene();
    // scene.background = new THREE.Color(0xf6eedc);
    scene.background = new THREE.Color(
      theme?.includes("light") ? 0xf6eedc : 0x1d222c
    );
    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      45,
      screenSize.width / screenSize.height,
      0.1,
      100
    );
    camera.position.set(2, 3, 9);
    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(screenSize.width, screenSize.height);
    roomModel.current?.appendChild(renderer.domElement);
    // 创建相机控件
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(0, 0, 0);
    controls.enablePan = false;
    controls.enableZoom = false;
    controls.autoRotate = true;
    controls.autoRotateSpeed = 0.5;
    controls.maxAzimuthAngle = Math.PI / 4;
    controls.minAzimuthAngle = -Math.PI / 6;
    controls.maxPolarAngle = Math.PI / 2;
    controls.minPolarAngle = Math.PI / 6;
    // 加载模型
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("/model/draco/");
    const gltfLoader = new GLTFLoader();
    gltfLoader.setDRACOLoader(dracoLoader);
    gltfLoader.load("/model/forest_house.glb", function (forestHouse) {
      forestHouse.scene.position.set(0, -3, -1);
      scene.add(forestHouse.scene);
      render();
    });
    // 渲染
    function render() {
      controls.update();
      renderer.render(scene, camera);
      requestAnimationFrame(render);
      if (
        controls.getAzimuthalAngle() >= Math.PI / 4 ||
        controls.getAzimuthalAngle() <= -Math.PI / 6
      ) {
        controls.autoRotateSpeed *= -1;
      }
    }
    render();
  }, [theme]);

  useEffect(() => {
    if (window.innerWidth <= 768) {
      screenSize.width = 360;
      screenSize.height = 300;
    } else if (window.innerWidth > 768 && window.innerWidth <= 1024) {
      screenSize.width = 760;
      screenSize.height = 600;
    }
    onLoadModel();
  }, [onLoadModel]);

  return <div ref={roomModel}></div>;
}

export default memo(Room);
